import UseWebsocket from '@/hooks/UseWebsocket';
import { message } from 'antd';
import { SetStateAction, useState,useCallback } from 'react';
// websocket 链接函数
export default function  useGlobalDataService(data?:any) {
  const [_, sendMessage, ] = UseWebsocket({
    url: 'ws://127.0.0.1:9909',  //链接地址
    onOpen: () => {
    //连接成功
      // console.log('链接成功')
    if(data != " "){
      sendMessage(data)
    }
    },
    onClose: () => {
    //连接关闭
    
      // message.error('请检查发卡器链接是否正常')
    },
    onError: (event) => {
    //连接异常
      console.error('WebSocket error:', event);
    },
    onMessage: (message) => {
    //收到消息
    if(data != " "){
      updateGlobalData(JSON.parse(message))
    }
     
 
    },
  });
  const [globalData, setGlobalData] = useState('');

  const updateGlobalData = useCallback((newData: SetStateAction<string>) => {
    setGlobalData(newData);
  }, [setGlobalData]);

  return { globalData, updateGlobalData };
}

